package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.SetmealDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.CheckGroup;
import com.itheima.pojo.Member;
import com.itheima.pojo.Setmeal;
import com.itheima.utils.DateUtils;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import java.io.*;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService {
    @Resource
    private JedisPool jedisPool;
    @Resource
    private SetmealDao setmealDao;
    @Resource
    private FreeMarkerConfigurer freeMarkerConfigurer;
    @Value("${out_put_path}") //从属性文件中读取要生成的html对应的目录
    private String outPutPath;
    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        setmealDao.add(setmeal);

        setSetmealAndCheckGroup(setmeal,checkgroupIds);

        //将图片名称保存到Redis中
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,setmeal.getImg());

        //当添加套餐后需要重新生成静态页面（套餐列表页面，套餐详情页面）
        //generateMobileStaticHtml();
    }

    //生成当前方法所需的静态页面
    public void generateMobileStaticHtml(){
        //在生成静态页面之前需要查询数据
        List<Setmeal> list = setmealDao.getSetmeal();
        //需要生成套餐列表静态页面
        generateMobileSetmealListHtml(list);
        //生成套餐详情静态页面（多个）
        generateMobileSetmealDetailHtml(list);
    }

    //生成套餐列表静态页面
    public void generateMobileSetmealListHtml(List<Setmeal> list){
        Map map = new HashMap();
        //为模板提供数据
        map.put("setmealList",list);
        this.generateHtml("mobile_setmeal.ftl","m_setmeal.html",map);
    }

    //生成套餐详情静态页面
    public void generateMobileSetmealDetailHtml(List<Setmeal> list){
        for (Setmeal setmeal : list) {
            Map map = new HashMap();
            map.put("setmeal",this.findById(setmeal.getId()));
            this.generateHtml("mobile_setmeal_detail.ftl","setmeal_detail_"+setmeal.getId()+".html",map);
        }
    }

    //通用的方法,用于生成静态页面
    public void generateHtml(String templateName, String htmlPageName, Map map){
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        //Writer writer = null;
        OutputStreamWriter writer = null;
        PrintWriter printWriter = null;

        try {
            //加载模板
            Template template = configuration.getTemplate(templateName);
            //构造输出流
            //writer = new FileWriter(outPutPath+"/"+htmlPageName);
            writer = new OutputStreamWriter(new FileOutputStream(outPutPath+"/"+htmlPageName), "UTF-8");
            printWriter = new PrintWriter(writer);
            //输出
            template.process(map,printWriter);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //关闭Writer对象
            if (printWriter != null) {
                printWriter.close();
            }
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage,pageSize);
        Page<Setmeal> setmealPage = setmealDao.findPage(queryString);
        return new PageResult(setmealPage.getTotal(),setmealPage.getResult());
    }

    @Override
    public List<Setmeal> getSetmeal() {
        return setmealDao.getSetmeal();
    }

    @Override
    public Setmeal findById(Integer id) {
        return setmealDao.findById(id);
    }

    @Override
    public List<Map<String, Object>> findsetmealCount() {
        return setmealDao.findsetmealCount();
    }

    @Override
    public List<Integer> findGroupIdBySetmealId(Integer id) {
        return setmealDao.findGroupIdBySetmealId(id);
    }

    @Override
    public void edit(Setmeal setmeal, Integer[] checkgroupIds) {
        //根据id查询原有图片的名称
        String imgName = setmealDao.findImgBysetmealID(setmeal.getId());

        jedisPool.getResource().srem(RedisConstant.SETMEAL_PIC_DB_RESOURCES,imgName);

        setmealDao.edit(setmeal);

        //将图片名称保存到Redis中
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,setmeal.getImg());

        setmealDao.deleteAssociation(setmeal.getId());

        setSetmealAndCheckGroup(setmeal,checkgroupIds);
    }

    @Override
    public void delete(Integer id) {
        //判断是否和检查组有关联
        List<Integer> ids = setmealDao.findGroupIdBySetmealId(id);
        if (ids!=null&&ids.size()>0){
            throw new RuntimeException("当前检查组被引用，不能删除");
        }

        String imgName = setmealDao.findImgBysetmealID(id);

        jedisPool.getResource().srem(RedisConstant.SETMEAL_PIC_DB_RESOURCES,imgName);

        setmealDao.delete(id);

        System.out.println("删除的图片："+imgName);
    }

    // 查询套餐收入占比
    @Override
    public List<Map<String, Object>> findSetmealIncomeStatistics() {
        return setmealDao.findSetmealIncomeStatistics();
    }




    //根据会员id获取全部套餐信息
    @Override
    public List<Map<String,Object>> findMemberBySetmeal(String telephone) {

        return setmealDao.findMemberBySetmeal(telephone);


    }

    //根据预约id获取预约记录
    @Override
    public Setmeal findSetmealById(Integer id) {

        return setmealDao.findSetmealById(id);



    }

    //根据提供日期范围查询当前会员历史预约记录的功能
    @Override
    public List<Map<String, Object>> findByPage(String[] times,String telePhone) throws Exception {

        Date begin = DateUtils.parseString2Date(times[0]);
        Date begin2 = DateUtils.parseString2Date(times[1]);

        return setmealDao.findByPage(begin,begin2,telePhone);
    }


    //新增绑定项
    public void setSetmealAndCheckGroup(Setmeal setmeal,Integer[] checkgroupIds){
        Integer setmealId = setmeal.getId();
        for (Integer checkgroupId : checkgroupIds) {
            setmealDao.setSetmealAndCheckGroup(setmealId,checkgroupId);
        }
    }

    @Override
    public List<Setmeal> findAll() {

        return setmealDao.findAll();
    }

}
